import React, { useEffect, useState, forwardRef } from 'react'
import store from '../../redux/store'
import { _getRegionList } from '../../api/user'
import { _getRoleList } from '../../api/role'
import { Form, Input, Select } from 'antd'
const { Option } = Select
const UserForm = forwardRef((props, ref) => {
  const [regionsList, setRegionsList] = useState([])
  const [roleList, setRoleList] = useState([])
  const [isDisable, setDisable] = useState(false)
  // 获取部门列表
  useEffect(() => {
    _getRegionList().then(res => {
      setRegionsList(res)
    })
  }, [])
  // 获取角色列表
  useEffect(() => {
    _getRoleList().then(res => {
      setRoleList(res)
    })
  }, [])
  useEffect(() => {
    if (props.type === '更新用户') {
      ref.current.setFieldsValue(props.currentFormLine)
      if (props.currentFormLine.region === "") {
        setDisable(true)
      }
    }
  }, [])
  const { role } = store.getState().userInfo[0]
  const { roleType } = role
  const changeRegion = (value) => {
    if (value === 1) {
      setDisable(true)
      ref.current.setFieldsValue({
        region: ""
      })
      return
    }
    setDisable(false)
  }
  return (
    <Form
      ref={ref}
      name="basic"
      labelCol={{ span: 5 }}
      autoComplete="off"
    >
      <Form.Item
        label="账号"
        name="useraccount"
        rules={[{ required: true, message: '请输入必填项内容' }, { min: 2, max: 15, message: '请输入2-15位字符' }]}>
        <Input allowClear />
      </Form.Item>
      <Form.Item
        label="用户名称"
        name="username"
        rules={[{ required: true, message: '请输入必填项内容' }, { min: 2, max: 15, message: '请输入2-15位字符' }]}>
        <Input allowClear />
      </Form.Item>
      <Form.Item
        label="用户密码"
        name="password"
        rules={[{ required: true, message: '请输入必填项内容' }]}>
        <Input allowClear />
      </Form.Item>
      <Form.Item
        label="部门"
        name="region"
        rules={isDisable ? [] : [{ required: true, message: '请输入必填项内容' }]}>
        <Select disabled={isDisable} allowClear>
          {regionsList.map(item => {
            return <Option disabled={item.id < role.id} key={item.id} value={item.value}>{item.title}</Option>
          })}
        </Select>
      </Form.Item>
      <Form.Item
        label="角色"
        name="roleId"
        rules={[{ required: true, message: '请输入必填项内容' }]}>
        <Select onChange={(value) => changeRegion(value)} allowClear>
          {roleList.map(item => {
            return <Option disabled={item.roleType < roleType} key={item.id} value={item.id}>{item.roleName}</Option>
          })}
        </Select>
      </Form.Item>
    </Form>
  )
})
export default UserForm